package com.free.freemarker.manager;

import java.io.File;
import java.io.IOException;

import com.free.freemarker.constant.Constant;
import com.free.freemarker.core.Builder;
import com.free.freemarker.core.SqlBuilder;
import com.free.freemarker.file.FileManager;

import com.free.freemarker.module.Model;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class Manager {

    private static Manager instance;
    private Configuration configuration;
    private Template template;
    private SqlBuilder sqlBuilder;

    private Manager(String path) throws IOException {
        configuration = new Configuration(Configuration.getVersion());
        configuration.setDirectoryForTemplateLoading(new File(path));
    }

    public static Manager getInstance(SqlBuilder sqlBuilder) {
        try {
            instance = new Manager(Constant.ftlPath);
            instance.sqlBuilder = sqlBuilder;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return instance;
    }

    public void getTemplate(String templateName) throws IOException {
        template = configuration.getTemplate(templateName);
    }

    public void builder(Builder builder, String tableName, String description) throws Exception {
        builder.builder(this, tableName, description);
    }


    /**
     * 通用 builder
     *
     * @param path         文件路径
     * @param fileName     文件名
     * @param suffix       后缀名
     * @param templateName 模板名
     * @param model        模板
     * @throws Exception
     */
    public void builder(String path, String fileName, String suffix, String templateName, Model model) throws Exception {
        File f = FileManager.create(path, fileName, suffix);
        getTemplate(templateName);
        FileManager.complete(template, f, model.getRoot());
    }

    public SqlBuilder getSqlBuilder() {
        return sqlBuilder;
    }
}
